<?php
/**
 * Created by PhpStorm.
 * User: zhangrxiang
 * Date: 17-2-17
 * Time: 下午9:16
 */


class Db{
    private static $_instance = null;//该类中的唯一一个实例
    private $dbConn;
    private function __construct(){//防止在外部实例化该类
        $this->dbConn = new MySQLi("localhost","root","root","test");
        $this->dbConn->query("set names utf8");
    }
    private function __clone(){}//禁止通过复制的方式实例化该类

    public static function getInstance(){
        if(self::$_instance == null){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function select($table){//数据库操作方法,后续可以继续完善和添加......
        $query = "select * from ".$table;
        $result = $this->dbConn->query($query);
        $result_arr = array();
        while($query = $result->fetch_assoc()){
            $result_arr[]    = $query;
        }
        return $result_arr;//结果集以数组的形式返回
    }

    public function insert($table, $data, $where = null)
    {
        if (is_array($data)) {
            $keys = '';
            $vals = '';
            foreach ($data as $key => $val) {

                $keys .=  $key . ",";
                if ($key == 'stu_pwd') {
                    $vals .= "password('$val'),";
                } elseif ($key == 'stu_age') {
                    $vals .= $val . ',';
                }else{
                    $vals .= "'". $val ."'" . ',';
                }
            }

            $query = "INSERT INTO $table (" . substr($keys, 0, strlen($keys) - 1) . ") VALUES (" . substr($vals, 0, strlen($vals) - 1) . ")";
            $result = $this->dbConn->query($query);
            if ($result){
                return $this->dbConn->insert_id;
            }else{
                return $result;
            }
        }
    }
}


/**
 * test
 */
//$db = db::getInstance();
//$id = $db->insert("test.student",[
//    "stu_name" => "zrx",
//    "stu_pwd" => "zrx",
//    "stu_age" => 22
//]);
//echo $id;